<template>
	<view>
      <van-search 
      background="#C00000" 
      :value="kw" 
      shape="round" 
      :focus="focus"
      placeholder="请输入搜索关键词"
       @change="getInput()"
       @search="search()"
      />
	</view>
</template>

<script>
	export default {
    created(){
      uni.getStorage({
        key:'history',
        success:(res)=>{
          this.historylist=res.data
        }
      })
    },
    props:{
      focus:{
        type:Boolean,
        default:false
      }
    },
		data() {
			return {
          kw:'',
          suggestlist:[],
          timer:null,
          historylist:[]
			};
		},
    
    methods:{
      // 获取搜索建议
      async getSuggest(k){
        const {data:res} = await uni.$http.get(`/api/public/v1/goods/qsearch?query=${k}`)
        this.suggestlist=res.message
      },
      // 设置防抖
      getInput(e){
        if(e.detail===''){
          this.suggestlist=[]
          uni.$emit('setSuggest',this.suggestlist)
          return
        }
        clearTimeout(this.timer)
        this.kw=e.detail
        this.timer=setTimeout(()=>{
          this.getSuggest(this.kw)
          uni.$emit('setSuggest',this.suggestlist)
          
        },3000)
      },
      // 发起搜索
      search(){
        // 把搜索关键词转存到历史数组
        this.historylist.push(this.kw)
        // 实现关键词的去重
        this.historylist=Array.from(new Set(this.historylist))
        this.setHistory()
      },
      // 存储搜索
      setHistory(){
        uni.setStorage({
          key:'history',
          data:this.historylist
        })
      }
    }
	}
</script>

<style>

</style>
